import { reactive } from 'vue'
import { articleRes, adduser, delectuser } from '@/api/recommend.js'
import { ElMessage } from 'element-plus'

const data = reactive({
  list: [],
  num: [],
  isbtns: false
})
let users = null
if (window.localStorage.getItem('user')) {
  users = JSON.parse(window.localStorage.getItem('user')).data
}

export default function getRecommendFun () {
  function requestArt () {
    articleRes({
      id: users.results[0].id
    }).then((res: any): void => {
      console.log(res)
      data.list = res.data.results
    })
  }
  function arry (_articlenumber: any) {
    for (let i = 0; i < data.num.length; i++) {
      if (_articlenumber === data.num[i]) {
        data.isbtns = true
      }
    }
  }
  function addattention (articlenumber: any, index: any) {
    if (data.num[index] !== undefined) {
      data.num[index] = null
      console.log(data.num)
      delectuser({
        articlenumber: articlenumber
      }).then((res: any) => {
        if (res.data.message === true) {
          ElMessage({
            showClose: true,
            message: '已经取消关注',
            type: 'warning'
          })
        }
      })
      return 0
    } else {
      data.num[index] = articlenumber
      console.log(data.num)
    }
    adduser({
      user: users.username,
      id: articlenumber
    }).then((res: any) => {
      console.log(res)
      if (res.data.message === true) {
        this.$message({
          type: 'success',
          message: '关注成功!'
        })
      }
    })
    arry(articlenumber)
  }
  return {
    data,
    requestArt,
    addattention
  }
}
